<template>
  <Drawer>
    <BaseForm />
  </Drawer>
</template>
<script lang="tsx" setup>
import type { PositionTypeItem } from '../type';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import {
  createPosition,
  getPositionById,
  updatePosition,
} from '#/api/sys/position';

import { schema } from '../columns';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
// 定义表单
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false, // 不显示操作按钮
  layout: 'vertical',
  schema,
});

// 定义弹窗
const [Drawer, drawerApi] = useVbenDrawer({
  loading: true, // 不显示加载中状态
  confirmLoading: false, // 不显示提交中状态
  // 表单校验
  async onConfirm() {
    const isPass =
      (await baseFormApi.validateAndSubmitForm()) as PositionTypeItem; // 校验表单
    const { type, id } = drawerApi.getData<Record<string, any>>();
    if (!isPass) {
      return; // 校验不通过
    }
    if (type === 'addData') {
      savePosition(isPass);
    }
    if (type === 'editData') {
      savePosition(isPass, id);
    }
  },
  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { type, id } = drawerApi.getData<Record<string, any>>();
      // 新增打开弹窗时重置表单
      if (type === 'addData') {
        drawerApi.setState({ loading: false, confirmLoading: false });
        baseFormApi.resetForm();
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getPositionDetailInfo(id);
      }
    }
  },
});

/**
 * @author Buke
 * @description 新增或编辑职位
 * @param {Record<string, any>} formData - 表单数据对象
 * @param {number} [id] - 职位ID（存在表示编辑，不存在表示新增）
 * @returns {void}
 */
async function savePosition(
  formData: PositionTypeItem,
  id?: number,
): Promise<void> {
  const data = {
    ...formData,
    id,
    sort: Number(formData.sort),
    status: Number(formData.status),
  };
  id ? await updatePosition(data) : await createPosition(data);
  ElMessage.success($t('common.operateSuccess'));
  emit('refresh');
}
/**
 * @author Buke
 * @description 详情数据回显
 * @param {number} id - 要回显的职位ID。
 * @returns {void}
 */
async function getPositionDetailInfo(id: number): Promise<void> {
  drawerApi.setState({ loading: true });
  await getPositionById(id).then((res: any) => {
    baseFormApi.setValues({
      ...res,
      status: String(res.status),
    });
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  });
}
</script>
